﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Beyondsoft.Tuanju.DataManager;

// “搜索合同”项模板在 http://go.microsoft.com/fwlink/?LinkId=234240 上提供

namespace Tuan
{
    /// <summary>
    /// 此页显示全局搜索定向到此应用程序时的搜索结果。
    /// </summary>
    public sealed partial class SearchResultsPage : Tuan.Common.LayoutAwarePage
    {
        private UIElement _previousContent;
        private ApplicationExecutionState _previousExecutionState;
        private string _queryText;

        public SearchResultsPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Determines how best to support navigation back to the previous application state.
        /// </summary>
        public static void Activate(String queryText, ApplicationExecutionState previousExecutionState)
        {
            var previousContent = Window.Current.Content;
            var frame = previousContent as Frame;

            if (frame != null)
            {
                // If the app is already running and uses top-level frame navigation we can just
                // navigate to the search results
                frame.Navigate(typeof(SearchResultsPage), queryText);
            }
            else
            {
                // Otherwise bypass navigation and provide the tools needed to emulate the back stack
                SearchResultsPage page = new SearchResultsPage();
                page._previousContent = previousContent;
                page._previousExecutionState = previousExecutionState;
                page.LoadState(queryText, null);
                Window.Current.Content = page;
            }

            // Either way, active the window
            Window.Current.Activate();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            this._queryText = navigationParameter as String;
            this._queryText = this._queryText.Trim();

            // TODO: Application-specific searching logic.  The search process is responsible for
            //       创建用户可选的结果类别列表:
            //
            //       filterList.Add(new Filter("<filter name>", <result count>));
            //
            //       仅第一个筛选器(通常为“全部”)应将 true 作为第三个参数传入
            //       以便以活动状态开始。活动筛选器的结果在
            //       下面的 Filter_SelectionChanged 中提供。

            var filterList = new List<Filter>();
            filterList.Add(new Filter("All", 0, true));

            // 通过视图模型沟通结果
            this.DefaultViewModel["QueryText"] = '\u201c' + this._queryText + '\u201d';
            this.DefaultViewModel["CityName"] = City.DefaultCity.CityName;
            this.DefaultViewModel["CanGoBack"] = this._previousContent != null;
            this.DefaultViewModel["Filters"] = filterList;
            this.DefaultViewModel["ShowFilters"] = filterList.Count > 1;            
        }

        /// <summary>
        /// 在按后退按钮时进行调用。
        /// </summary>
        /// <param name="sender">表示后退按钮的 Button 实例。</param>
        /// <param name="e">描述如何单击按钮的事件数据。</param>
        protected override void GoBack(object sender, RoutedEventArgs e)
        {
            // 将应用程序返回到请求搜索结果之前的状态。
            if (this.Frame != null && this.Frame.CanGoBack)
            {
                this.Frame.GoBack();
            }
            else if (this._previousContent != null)
            {
                Window.Current.Content = this._previousContent;
            }
            else
            {
                // TODO: invoke the app's normal launch behavior, using this._previousExecutionState
                //       as appropriate.  Exact details can vary from app to app, which is why an
                //       implementation isn't included in the Search Contract template.  Typically
                //       this method and OnLaunched in App.xaml.cs can call a common method.
            }
        }

    /// <summary>
        /// 在使用处于对齐视图状态的 ComboBox 选择筛选器时进行调用。
        /// </summary>
        /// <param name="sender">ComboBox 实例。</param>
        /// <param name="e">描述如何更改选定筛选器的事件数据。</param>
        async void Filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 确定选定的筛选器
            var selectedFilter = e.AddedItems.FirstOrDefault() as Filter;
            if (selectedFilter != null)
            {
                // 将结果镜像到相应的筛选器对象中，以允许
                // 在未对齐以反映更改时使用的 RadioButton 表示形式
                selectedFilter.Active = true;

                VisualStateManager.GoToState(this, "Loading", true);
                IEnumerable<Deal> deals = await City.DefaultCity.GetDeals(this._queryText);
                this.DefaultViewModel["Results"] = deals;
                VisualStateManager.GoToState(this, deals.Count() > 0 ? "ResultsFound" : "NoResultsFound", true);
            }
        }

        /// <summary>
        /// Navigating to ItemDetailsPage when click some deal
        /// </summary>
        /// <param name="sender">Grid view item</param>
        /// <param name="e">Selected view item</param>
        private void ResultsGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var itemId = ((Deal)e.ClickedItem).Gid;
            this.Frame.Navigate(typeof(ItemDetailsPage), itemId);
        }

        /// <summary>
        /// 在未对齐的情况下使用 RadioButton 选定筛选器时进行调用。
        /// </summary>
        /// <param name="sender">选定的 RadioButton 实例。</param>
        /// <param name="e">描述如何选定 RadioButton 的事件数据。</param>
        void Filter_Checked(object sender, RoutedEventArgs e)
        {
            // 将更改镜像到对应的 ComboBox 使用的 CollectionViewSource 中
            // 以确保在对齐后反映更改
            if (filtersViewSource.View != null)
            {
                var filter = (sender as FrameworkElement).DataContext;
                filtersViewSource.View.MoveCurrentTo(filter);
            }
        }

        /// <summary>
        /// 描述可用于查看搜索结果的筛选器之一的视图模型。
        /// </summary>
        private sealed class Filter : Tuan.Common.BindableBase
        {
            private String _name;
            private int _count;
            private bool _active;

            public Filter(String name, int count, bool active = false)
            {
                this.Name = name;
                this.Count = count;
                this.Active = active;
            }

            public override String ToString()
            {
                return Description;
            }

            public String Name
            {
                get { return _name; }
                set { if (this.SetProperty(ref _name, value)) this.OnPropertyChanged("Description"); }
            }

            public int Count
            {
                get { return _count; }
                set { if (this.SetProperty(ref _count, value)) this.OnPropertyChanged("Description"); }
            }

            public bool Active
            {
                get { return _active; }
                set { this.SetProperty(ref _active, value); }
            }

            public String Description
            {
                get { return String.Format("{0} ({1})", _name, _count); }
            }
        }
    }
}
